package design_pattern.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class LoadBalancer {
    //私有静态成员变量，存储唯一实例
    private static volatile LoadBalancer instance = null;
    //服务器集合
    private List<String> serverList = null;

    //private禁止new出这个实例对象
    private LoadBalancer() {
        serverList = new ArrayList<>();
    }

    //公有静态实例方法，返回唯一实例,懒加载，不是在类加载时就创建在用的时候创建
    public static LoadBalancer getLoadBalancer() {

        if (instance == null) {
            synchronized (LoadBalancer.class) {
                if (instance == null) {
                    instance = new LoadBalancer();
                }
            }
        }
        return instance;
    }

    public void addServer(String server) {
        serverList.add(server);
    }

    public void removeServer(String server) {
        serverList.remove(server);
    }

    public String getServer() {
        Random random = new Random();
        int i = random.nextInt(serverList.size());
        return (String) serverList.get(i);
    }
}
